<template>
  <el-div class="navbar">
        <el-div class="navbar-left">
            <a @click="goBackHome" class="dropbtn"><el-i class="fas fa-home"></el-i></a> 
            <el-p class="welcome-message">{{message}}</el-p>
        </el-div>
      <el-div class="navbar-center">
          <el-div class="dropdown">
              <a class="dropbtn">文章</a>
              <el-div class="dropdown-content">
                  <a @click="goToAllBoke"><i class="fas fa-list"></i>文章列表</a>
                  <a @click="goToBokeColumn"><i class="fas fa-th-large"></i>文章分类</a>
                  <a href="#"><i class="fas fa-tags"></i>文章标签</a>
                  <a href="#"><i class="fas fa-book"></i>即时短文</a>
              </el-div>
          </el-div>
          <a target="_blank" href="http://bilibili.com" class="dropbtn">友链</a>
          <el-div class="dropdown">
              <a class="dropbtn" @click="goToUserUpdate">我的</a>
              <el-div class="dropdown-content">
                  <a @click="goToMyBlog(UserID)"><i class="fa fa-blog"></i>我的博客</a>
                  <a @click="goToAddBoke"><i class="fas fa-edit"></i>发布博客</a>
                  <a href="#"><i class="fa fa-file-powerpoint"></i>PPT收藏</a>
              </el-div>
          </el-div>
  
      </el-div>
      <el-div class="navbar-right">
          <a href="#"><i class="fas fa-book"></i></a>
          <a href="#"><i class="fas fa-podcast"></i></a>
          <a href="#"><i class="fas fa-search"></i></a>
          <el-div class="dropdown">
              <a href="#" class="dropbtn"><i class="fa fa-cog"></i></a>
              <el-div class="dropdown-content" style="position: absolute; left: auto; right: 0; transform: translateX(0); min-width: 150px;">
                  <a href="#" id="theme-toggle"><i id="theme-icon" class="fas fa-moon" @click="toggleTheme"></i></a>
                  <a @click="goBackLogin"><i class="fas fa-sign-out-alt"></i> 退出登录</a>
              </el-div>
          </el-div>
      </el-div>
  </el-div>
  <div class="container">
  <div class="intro-container">
    <div class="tags">
      <div class="tag">{{ boke.ColumnNames }}</div>
      <div class="tag no-background">
        <i class="fas fa-hashtag"></i> {{ boke.TagNames }}
      </div>
    </div>
    <h1>{{ boke.PostTitle }}</h1>
    <div class="info">
      <div>
        <i class="fas fa-calendar-alt"></i>
        {{ boke.Post_Date }}
      </div>
      <div>
        <i class="fas fa-user"></i>
        {{ boke.UserName }}
      </div>
      <div>
        <i class="fas fa-eye"></i>
        {{ boke.Post_Views }}
      </div>
      <div class="tag" style="cursor: pointer;" :class="{ 'liked': isLiked }">
        <div @click="toggleLike()">
          <i :class="isLiked ? 'fas fa-thumbs-up' : 'far fa-thumbs-up'"></i>
          {{ thumbs }}
        </div>
      </div>
      <div @click="showComment">
        <i class="fas fa-comment"></i>
        {{ commentnum }}
      </div>
    </div>
  </div>
  <div class="content-wrapper">
    <div class="main-content">
      <div class="section" id="proxy-pattern">
        <p>{{ boke.PostContent }}</p>
      </div>
    </div>
    <div class="sidebar">
      <div class="profile">
        <img src="/src/assets/cat.gif" alt="Profile Picture">
        <h3>随风起</h3>
        <p>分享知识与美好时光</p>
        <div>
          <a href="https://github.com"><i class="fab fa-github"></i></a>
          <a href="https://mail.qq.com"><i class="fas fa-envelope"></i></a>
        </div>
      </div>
      <div class="announcement">
        <h4>公告</h4>
        <p>欢迎来到我的博客</p>
      </div>
    </div>
  </div>
</div>
<div class="comment-container">
        <h3>评论区</h3>
        <div class="comments">
          <ul>
            <li v-for="(comment, index) in comments" :key="index" class="comment-item">
              <div class="comment-header">
                <span class="comment-username">{{ comment.userName }}</span>
                <span class="comment-date">{{ comment.date }}</span>
              </div>
              <div class="comment-content">
                {{ comment.CommentContent }}
              </div>
              <hr class="comment-divider" />
            </li>
          </ul>
        </div>
      </div>

      <div class="comment-form">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" @submit.prevent="addComment">
          <el-form-item label="评论内容" prop="commentContent">
            <el-input type="textarea" v-model="form.commentContent"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addComment">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'; // 确保导入 onMounted
import { useRoute, useRouter } from 'vue-router';
import instance from '../api/server';
// import CommentView from '../pages/CommentView.vue';

// const isModalVisible = ref(false);
const comments = ref([]);
const thumbs = ref({});
const isLiked = ref(false);
console.log(isLiked.value + "完成了");
const commentnum = ref({});
const route = useRoute();
const router = useRouter();
const form = ref({
  commentContent: ''
});
const boke = ref({});
const showComment = async () => {
    try {
      const postId = route.params.PostId;
      const commentResponse = await instance.get(`/myinfo/blog/getcommentbypostid/${postId}`);
      console.log(JSON.stringify(commentResponse.data, null, 2));  

      if (commentResponse.data && commentResponse.data.data && commentResponse.data.data.length > 0) {
        comments.value = commentResponse.data.data;
      } else {
        console.error("数据为空，无法获取评论信息");
      }
    } catch (error) {
      console.error("获取评论时发生错误: ", error);
    }
  };
  const addComment = async () => {
  console.log("点击了提交按钮");
  console.log(form.value.commentContent); // 注意这里需要使用 form.value.commentContent
  try {
    const postId = route.params.PostId;
    const response = await instance.post(`/myinfo/blog/addcomment/${postId}`, {
      commentContent: form.value.commentContent
    });
    if (response.data && !response.data.status) {
      console.log("评论添加成功");
      showComment();
      window.location.reload();
    }
  } catch (error) {
    console.error("添加评论时发生错误: ", error);
  }
};

const fetchPosts = async () => {
    try {
        const postId = route.params.PostId;
        const response = await instance.get(`/myinfo/blog/getpostdetail/${postId}`); 
        console.log(JSON.stringify(response.data, null, 2)); // 以格式化的方式打印对象

        if (response.data && response.data.data && response.data.data.length > 0) {
            boke.value = response.data.data[0];
            console.log(boke.value, "魏晨魏晨魏晨"); // 直接打印对象
            console.log(boke.value.PostTitle); // 确保 boke.value 是对象并访问其属性
        } else {
            console.error("数据为空，无法获取博客信息");
            console.log(JSON.stringify(response.data, null, 2));
        }
    } catch (error) {
        console.error("API 请求错误: ", error);
    }
};

const getThumbs = async () => {
    try {
        const postId = route.params.PostId;
        const thumbResponse = await instance.get(`/myinfo/blog/getthumbcount/${postId}`);
        
        if (thumbResponse.data && typeof thumbResponse.data.data === 'number') {
            console.log(`点赞数: ${thumbResponse.data.data}`);
            // 这里可以将点赞数赋值给某个变量，以便在模板中使用
            thumbs.value = thumbResponse.data.data;
        } else {
            console.error("点赞数据无效或缺失");
            console.log(JSON.stringify(thumbResponse.data, null, 2));
        }
    } catch (error) {
        console.error("获取点赞数时发生错误: ", error);
    }
};

const getCommentNum = async () => {
    try {
        const postId = route.params.PostId;
        const commentResponse = await instance.get(`/myinfo/blog/getcommentnumbypostid/${postId}`);
        
        if (commentResponse.data && typeof commentResponse.data.data === 'number') {
            console.log(`评论数: ${commentResponse.data.data}`);
            commentnum.value = commentResponse.data.data;
        } else {
            console.error("点赞数据无效或缺失");
            console.log(JSON.stringify(commentResponse.data, null, 2));
        }
    } catch (error) {
        console.error("获取点赞数时发生错误: ", error);
    }
};

const toggleLike = async () => {
    try {
        const postId = route.params.PostId;
        const isthumbresponse = await instance.get(`/myinfo/blog/thumb/${postId}`);
        
        if (isthumbresponse.data.status === 0) {
            isLiked.value = !isLiked.value;
            thumbs.value += isLiked.value ? 1 : -1;
          
        } else {
            console.error("点赞操作失败");
            console.log(isthumbresponse.data.message);
        }
    } catch (error) {
        console.error("点赞请求错误: ", error);
    }
};

const Post_Views = async () => {
    try {
        const postId = route.params.PostId;
        const addcommentResponse = await instance.get(`/myinfo/blog/addpostviews/${postId}`);
        if (addcommentResponse.data.status === 0) {
            console.log("浏览量增加成功");
        } else {
            console.error("浏览量增加失败");
        }
    } catch (error) {
        console.error("获取点赞数时发生错误: ", error);
    }
};

const goToMyBlog = (UserID) => {
    router.push(`/myboke/${UserID}`).then(() => {
        window.location.reload();
    });
};

// const showComment = async() => {
//   try{
//     isModalVisible.value = true;
//     const postId = route.params.PostId;
//     const commentResponse = await instance.get(`/myinfo/blog/getcommentbypostid/${postId}`);
//     if (commentResponse.data && commentResponse.data.data && commentResponse.data.data.length > 0) {
//       comments.value = commentResponse.data.data;
      
//     } else {
//       console.error("数据为空，无法获取评论信息");
//       console.log(JSON.stringify(commentResponse.data, null, 2));
//     }
//   }catch (error) {
//     console.error("获取评论时发生错误: ", error);
//   }
// };

// const closeComment = () => {
//   isModalVisible.value = false;
// };

// const addComment = async (newCommentContent) => {
//   // 检查评论内容是否为空
//   if (!newCommentContent.trim()) {
//     alert('评论内容不能为空');
//     return;
//   }

//   console.log("评论内容：", newCommentContent);

//   try {
//     // 获取 PostId 参数
//     const postId = route.params.PostId; 
//     console.log("请求的 PostId: ", postId);

//     // 发送请求
//     const response = await instance.post(`/myinfo/blog/addcomment/${postId}`, { content: newCommentContent });
//     console.log("评论返回：", response.data);

//     // 检查返回的状态
//     if (response.data.status === 0) {
//       console.log("评论成功");
//       // 更新评论列表
//       commentContent.value.unshift({ CommentContent: newCommentContent });

//     } else {
//       console.error("评论失败: ", response.data.message);
//       alert(response.data.message); // 显示后端返回的错误信息
//     }
//   } catch (error) {
//     console.error("添加评论时发生错误: ", error);
//     alert("添加评论时发生错误，请稍后再试！");
//   }
// };


onMounted(() => {
    fetchPosts();
    getThumbs();
    getCommentNum();
    Post_Views();
    showComment();
});

// 路由跳转方法
function goBackHome() {
  router.push("/home");
}

const goBackLogin = () => {
  localStorage.removeItem('token');
  localStorage.removeItem('userInfo');
  router.push("/").then(() => {
    window.location.reload();
  });
};

const goToUserUpdate = () => {
  router.push("/userupdate").then(() => {
    window.location.reload();
  });
};

const goToBokeColumn = () => {
  router.push("/bokecolumn").then(() => {
    window.location.reload();
  });
};

const goToAddBoke = () => {
  router.push("/addbokeinfo").then(() => {
    window.location.reload();
  });
};
</script>

<script>
  document.addEventListener('DOMContentLoaded', function() {
        var dropdowns = document.querySelectorAll('.dropdown');

        dropdowns.forEach(function(dropdown) {
            var dropdownContent = dropdown.querySelector('.dropdown-content');
            var timeout;

            dropdown.addEventListener('mouseenter', function() {
                clearTimeout(timeout);
                dropdownContent.style.display = 'flex';
                setTimeout(function() {
                    dropdownContent.style.opacity = '1';
                    dropdownContent.style.visibility = 'visible';
                }, 10);
            });

            dropdown.addEventListener('mouseleave', function() {
                timeout = setTimeout(function() {
                    dropdownContent.style.opacity = '0';
                    dropdownContent.style.visibility = 'hidden';
                    setTimeout(function() {
                        dropdownContent.style.display = 'none';
                    }, 500);
                }, 100);
            });

            dropdownContent.addEventListener('mouseenter', function() {
                clearTimeout(timeout);
            });

            dropdownContent.addEventListener('mouseleave', function() {
                timeout = setTimeout(function() {
                    dropdownContent.style.opacity = '0';
                    dropdownContent.style.visibility = 'hidden';
                    setTimeout(function() {
                        dropdownContent.style.display = 'none';
                    }, 1000);
                }, 200);
            });
        });
    });
</script>

<style src="../assets/style/bokeinfo.css"></style>